package com.psy.counseling.utils;

import com.deepoove.poi.XWPFTemplate;
import com.deepoove.poi.util.PoitlIOUtils;
import com.psy.counseling.entity.Ask;
import lombok.Data;

import java.io.*;
import java.util.HashMap;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

/**
 * ClassName:WorldUtil
 * Package:com.psy.counseling.utils
 * Description:
 *
 * @Date:2022/6/1 16:29
 * @Author:cxh
 */
@Data
public class WordUtil {
    public static XWPFTemplate toWord(Ask ask, String templatePath) throws IOException {
        XWPFTemplate template = XWPFTemplate.compile(templatePath).render(
                new HashMap<String, Object>() {{
                    put("sno", ask.getSno());
                    put("realName", ask.getRealName());
                    put("sex", ask.getSex());
                    put("faculty", ask.getFaculty());
                    put("telephone", ask.getTelephone());
                    put("type", ask.getType());
                    put("total", ask.getTotal());
                    put("report", ask.getReport());
                }});
        return template;
    }

    /**
     * 将文件添加到压缩包
     * @param filePath
     * @param zipOut
     * @throws IOException
     */
    public static void fileToZip(String filePath, ZipOutputStream zipOut) throws IOException {
        // 需要压缩的文件
        File file = new File(filePath);
        // 获取文件名称,如果有特殊命名需求,可以将参数列表拓展,传fileName
        String fileName = file.getName();
        FileInputStream fileInput = new FileInputStream(filePath);
        // 缓冲
        byte[] bufferArea = new byte[1024 * 10];
        BufferedInputStream bufferStream = new BufferedInputStream(fileInput, 1024 * 10);
        // 将当前文件作为一个zip实体写入压缩流,fileName代表压缩文件中的文件名称
        zipOut.putNextEntry(new ZipEntry(fileName));
        int length = 0;
        // 最常规IO操作,不必紧张
        while ((length = bufferStream.read(bufferArea, 0, 1024 * 10)) != -1) {
            zipOut.write(bufferArea, 0, length);
        }
        //关闭流
        fileInput.close();
        // 需要注意的是缓冲流必须要关闭流,否则输出无效
        bufferStream.close();
        // 压缩流不必关闭,使用完后再关
    }
}
